import waves from "@/directive/waves";
import { mapGetters } from 'vuex';
// components
import Pagination from "@/components/Pagination";
import CreateUser from './components/create-user/create-user'
import DetailUser from './components/detail-user/detail-user'
import DepartmentDetail from '../../organization-manage/department-manage/components/department-detail/department-detail';
// service
import { alertMessage, getTreeData, alertHtmlWithCallback, showAlertMessage } from '../../../utils/utils';
import { getSysStructsTreeApi, getRoleListApi, getUserListApi, deleteUserApi, resetPasswordApi } from './user-manage.service';

export default {
  name: 'user-manage',
  components: { Pagination, CreateUser, DetailUser, DepartmentDetail },
  directives: { waves },
  data() {
    return {
      loading: true, // table loading
      file_url: process.env.VUE_APP_FILE_URL, // 头像url
      // 筛选
      searchForm: {}, // 搜索内容
      confirmSearchForm: {}, // 确认提交搜索内容
      roles: [], // 职位列表
      structs: [], // 组织架构
      defaultProps: { // 部门树变量
        children: "children",
        label: "name",
        value: 'objectId',
        multiple: true,
        emitPath: false
      },
      // table列表分页
      checkedRows: [], // 批量选中的数据
      selectRow: {}, // 列表选中的行
      data: [], // 列表数据
      pageNum: 1, // 页码
      recordNum: 10, // 条数
      totalNum: 0, // 总数
      // ------
      type: '', // 弹窗类型 edit:编辑;password:重置密码
      departmentDetailDialogVisible: false, // 部门详情模态窗
      detailDialogVisible: false, // 用户详情模态窗
      editDialogVisible: false // 编辑详情模态窗
    }
  },
  computed: {
    ...mapGetters([
      'codesCheck'
    ])
  },
  created() {
    this.getDataList();
    this.getSysStruct();
  },
  methods: {
    setIndex(index) {
      return (this.pageNum - 1) * this.recordNum + index + 1;
    },

    // 职位远程搜索
    async remoteMethod(query) {
      this.roles = await this.getSysRole(query)
    },

    // 获取职位列表(角色)
    getSysRole(queryStr) {
      const data = {
        queryStr: queryStr,
        pageNum: 1,
        recordNum: 20
      }
      return new Promise(resolve => {
        getRoleListApi(data).then(res => {
          const roles = res.data
          resolve(roles)
        })
      })
    },

    // 获取部门列表
    getSysStruct() {
      getSysStructsTreeApi().then(res => {
        this.structs = getTreeData(res.data);
      });
    },

    // 获取列表
    getDataList() {
      this.loading = true;
      const params = {
        queryStr: this.confirmSearchForm.queryStr,
        roleIds: this.confirmSearchForm.roleIds,
        structIds: this.confirmSearchForm.structIds,
        pageNum: this.pageNum,
        recordNum: this.recordNum
      }
      getUserListApi(params).then(res => {
        this.totalNum = Number(res.dataCount);
        this.data = res.data;
        this.loading = false;
      });
    },

    // 重置密码
    resetPassword(row) {
      const message = {
        userName: row.userName,
        trueName: row.trueName,
        mobileNumber: row.mobileNumber,
        roleNames: row.roleNames,
        sex: row.sex,
        structName: row.structName,
        structCode: row.structCode
      }
      const alertMsg = showAlertMessage(`请确认用户信息`, message)
      alertHtmlWithCallback(alertMsg, `确认要重置该用户的密码吗?`, '确认重置').then(yes => {
        if (yes) {
          resetPasswordApi(row.objectId).then(res => {
            alertMessage(res.message)
          })
        }
      })
    },

    // 打开部门详情窗体
    openDepartmentDetailDialog(row) {
      this.selectRow = row;
      this.departmentDetailDialogVisible = true;
    },

    // 关闭部门详情窗体
    closeDepartmentDetailDialog() {
      this.departmentDetailDialogVisible = false;
    },

    // 刷新树
    reload() {
      this.pageNum = 1;
      this.onReset()
    },

    // 搜索列表
    search() {
      this.pageNum = 1;
      this.confirmSearchForm = JSON.parse(JSON.stringify(this.searchForm));
      this.getDataList();
    },

    // 刷新列表
    onReset() {
      this.pageNum = 1;
      this.confirmSearchForm = {
        queryStr: '',
        roleIds: [],
        structIds: []
      }
      this.searchForm = JSON.parse(JSON.stringify(this.confirmSearchForm))
      this.getDataList();
    },

    // 打开新建、编辑窗体
    openCreateOrEditDialog(id) {
      this.selectUserId = id;
      this.editDialogVisible = true;
    },

    // 打开详情弹窗
    openDetailDialog(type, id) {
      this.type = type;
      this.selectUserId = id;
      this.detailDialogVisible = true;
    },

    // 关闭新建、编辑窗体
    closeCreateOrEditDialog() {
      this.editDialogVisible = false;
      this.detailDialogVisible = false;
    },

    // 处理checkbox选中行数据
    handleSelectionChange(val) {
      this.checkedRows = val;
    },

    // 删除单/多条选中数据
    deleteSelectedData(id, name) {
      // 如果是单条删除
      let ids = id ? [id] : []
      if (ids.length === 0 && this.checkedRows.length === 0) {
        alertMessage('请至少选择一条数据', 'warning');
      } else {
        const message = {
          name: ids.length === 0 ? this.checkedRows.map(v => v.userName).join('&nbsp;&nbsp;') : name
        }
        const alertMsg = showAlertMessage(`用户名称为:`, message)
        alertHtmlWithCallback(alertMsg, `是否确认删除已选中的${ids.length === 0 ? this.checkedRows.length : 1}条数据`).then(() => {
          if (ids.length === 0) {
            this.checkedRows.forEach(item => {
              ids.push(item.objectId)
            });
          }
          deleteUserApi(ids).then((res) => {
            alertMessage(res.message);
            this.onReset();
          }).catch(() => { }); // 关闭confirm框的回调，不处理的话会报一个js error
        }).catch(() => { }); // 关闭confirm框的回调，不处理的话会报一个js error
      }
    }
  }
}
